package com.leyou.user.service;

import com.github.pagehelper.Page;
import com.leyou.common.utils.NumberUtils;
import com.leyou.user.mapper.AddressMapper;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.Address;
import com.leyou.user.pojo.User;
import com.leyou.user.utils.CodecUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: taft
 * @Date: 2018-10-24 10:54
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AddressMapper addressMapper;

    static final String KEY_PREFIX = "user:code:phone:";

    public Boolean check(String data, Integer type) {

        User user = new User();

        switch (type){
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
        }


        return this.userMapper.selectCount(user)!=1;
    }

    public void sendVerifyCode(String phone) {

        String code = NumberUtils.generateCode(7);


        Map<String,String> result = new HashMap<>();
        result.put("code",code);
        result.put("phone",phone);

        amqpTemplate.convertAndSend("ly.sms.exchange","sms.verify.code",result);

        //发送消息并且指定消息的生命周期
        redisTemplate.opsForValue().set(KEY_PREFIX+phone,code,5, TimeUnit.MINUTES);
    }

    /**
     *
     * 注册业务应该先校验验证码
     * */
    @Transactional
    public Boolean register(User user, String code) {
        String storeCode = redisTemplate.opsForValue().get(KEY_PREFIX+user.getPhone());



        //验证码校验通过
        if (StringUtils.isNotBlank(code)&&code.equals(storeCode)){
            //产生盐值，进行加密

            String salt = CodecUtils.generateSalt();

            user.setPassword(CodecUtils.md5Hex(user.getPassword(),salt));

            user.setSalt(salt);

            user.setCreated(new Date());

            //TODO 一切OK后redis中的数据是不是应该删除？？？？
            boolean flag = this.userMapper.insertSelective(user)==1;

            //覆盖原有的Redis值
            this.redisTemplate.opsForValue().set(KEY_PREFIX+user.getPhone(),"",1,TimeUnit.MILLISECONDS);
            return flag;


    }

        return null;
    }

    public User queryUser(String username, String password) {
        User user = new User();
        user.setUsername(username);
        User storeUser = this.userMapper.selectOne(user);


        String newpass =  CodecUtils.md5Hex(password,storeUser.getSalt());

        //使用合成密码来校验数据库中存储的密码，如果相等说明校验通过
        if (StringUtils.isNotBlank(newpass)&&newpass.equals(storeUser.getPassword())){
            return storeUser;
        }
        return null;
    }

    public List<Address> queryAddresses(Long Id,Long userId){
        Address address = new Address();
        address.setUserId(userId);
        return addressMapper.selectAll();


    }
}
